package com.gkj.blog.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.gkj.blog.business.service.TypeService;
import com.gkj.blog.business.vo.entity.TypeVo;
import com.gkj.blog.framework.holder.RequestHolder;
import com.gkj.blog.framework.object.AbstractServiceImpl;
import com.gkj.blog.persistence.mapper.TypeMapper;
import com.gkj.blog.persistence.po.Type;
import com.gkj.blog.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
@CacheConfig(cacheNames = "redis")
public class TypeServiceImpl extends AbstractServiceImpl<TypeVo,Type> implements TypeService {
    private TypeMapper typeMapper;

    @Autowired
    public void setTypeMapper(TypeMapper typeMapper) {
        this.typeMapper = typeMapper;
        setBaseMapper(typeMapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "'allTypes'")
    public boolean delete(Long id) {
        return super.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "'allTypes'")
    public boolean deleteIds(Long[] ids){
        return super.deleteIds(ids);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "'allTypes'")
    public TypeVo insert(TypeVo record) {
       return super.insert(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "'allTypes'")
    public boolean update(TypeVo record) {
        return super.update(record);
    }

    @Override
    @Cacheable(key="'allTypes'")
    public List<TypeVo> listAllType() {
        PageHelper.startPage(1,100);
        List<Type> poList=typeMapper.selectAll();
        List<TypeVo> voList=new LinkedList<>();
        poList.forEach((type)->{
            voList.add(new TypeVo(type));
        });
        return voList;
    }

    @Override
    @Cacheable(key = "'type_name_'+#name")
    public TypeVo getByTypeName(String name) {
        Type type = typeMapper.getByTypeName(name);
        RequestHolder.getSession().getServletContext().setAttribute("type_name_"+name,type);
        return new TypeVo(type);
    }
}
